import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker_plus/flutter_datetime_picker_plus.dart'
    as picker;
import '../models/moment.dart';
import '../services/moment_service.dart';
import 'moment_detail_page.dart';

class CreateMomentPage extends StatefulWidget {
  final Moment? moment; // 如果传入moment则为编辑模式

  const CreateMomentPage({
    super.key,
    this.moment,
  });

  @override
  State<CreateMomentPage> createState() => _CreateMomentPageState();
}

class _CreateMomentPageState extends State<CreateMomentPage> {
  final TextEditingController _titleController = TextEditingController();
  final TextEditingController _contentController = TextEditingController();
  final TextEditingController _createdTimeController = TextEditingController();
  late final MomentService _momentService;
  bool _isSubmitting = false;
  DateTime? _selectedDateTime;

  @override
  void initState() {
    super.initState();
    // 初始化MomentService，传入401回调
    _momentService = MomentService(
      onUnauthorized: _handleUnauthorized,
    );
    // 如果是编辑模式，填充原有内容
    if (widget.moment != null) {
      _titleController.text = widget.moment!.title ?? '';
      _contentController.text = widget.moment!.content;
      _createdTimeController.text = widget.moment!.createdTime;
      // 尝试解析已有的创建时间
      try {
        _selectedDateTime = DateTime.parse(widget.moment!.createdTime);
      } catch (e) {
        // 解析失败则忽略
      }
    }
  }

  // 处理401未授权，跳转到登录页
  void _handleUnauthorized() {
    Navigator.of(context).pushReplacementNamed('/login');
  }

  @override
  void dispose() {
    _titleController.dispose();
    _contentController.dispose();
    _createdTimeController.dispose();
    super.dispose();
  }

  bool get _isEditMode => widget.moment != null;

  Future<void> _selectDateTime() async {
    picker.DatePicker.showDateTimePicker(
      context,
      showTitleActions: true,
      minTime: DateTime(2000, 1, 1),
      maxTime: DateTime(2100, 12, 31),
      currentTime: _selectedDateTime ?? DateTime.now(),
      locale: picker.LocaleType.zh,
      onConfirm: (date) {
        setState(() {
          _selectedDateTime = date;
          // 格式化为标准格式：yyyy-MM-dd HH:mm:ss
          final year = _selectedDateTime!.year;
          final month = _selectedDateTime!.month.toString().padLeft(2, '0');
          final day = _selectedDateTime!.day.toString().padLeft(2, '0');
          final hour = _selectedDateTime!.hour.toString().padLeft(2, '0');
          final minute = _selectedDateTime!.minute.toString().padLeft(2, '0');
          final second = _selectedDateTime!.second.toString().padLeft(2, '0');
          _createdTimeController.text = '$year-$month-$day $hour:$minute:$second';
        });
      },
    );
  }

  void _clearDateTime() {
    setState(() {
      _selectedDateTime = null;
      _createdTimeController.clear();
    });
  }

  Future<void> _submitMoment() async {
    final title = _titleController.text.trim();
    final content = _contentController.text.trim();
    final createdTime = _createdTimeController.text.trim();

    if (content.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请输入内容')),
      );
      return;
    }

    setState(() {
      _isSubmitting = true;
    });

    try {
      if (_isEditMode) {
        // 编辑模式：先更新，然后调用详情接口获取最新数据
        await _momentService.updateMoment(
          widget.moment!.id,
          content,
          title: title.isNotEmpty ? title : null,
          createdTime: createdTime.isNotEmpty ? createdTime : null,
        );

        // 更新成功后，调用详情接口获取最新数据
        final moment = await _momentService.getMomentDetail(widget.moment!.id);

        if (mounted) {
          // 返回 Moment 对象，用于跳转到详情页
          Navigator.pop(context, moment);
        }
      } else {
        // 创建模式：直接使用返回的 Moment 对象
        final moment = await _momentService.createMoment(
          content,
          title: title.isNotEmpty ? title : null,
          createdTime: createdTime.isNotEmpty ? createdTime : null,
        );

        if (mounted) {
          // 直接替换为详情页，避免返回首页造成闪动
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(
              builder: (context) => MomentDetailPage(moment: moment),
            ),
          );
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('${_isEditMode ? "更新" : "创建"}失败: $e')),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isSubmitting = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFFFFFFF),
      appBar: AppBar(
        title: Text(_isEditMode ? '编辑' : '新增'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        actions: [
          TextButton(
            onPressed: _isSubmitting ? null : _submitMoment,
            child: _isSubmitting
                ? const SizedBox(
                    width: 20,
                    height: 20,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      color: Colors.white,
                    ),
                  )
                : const Text(
                    '发布',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16,
                    ),
                  ),
          ),
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 标题输入框
            TextField(
              controller: _titleController,
              decoration: const InputDecoration(
                hintText: '标题',
                border: InputBorder.none,
                hintStyle: TextStyle(
                  color: Colors.grey,
                  fontSize: 18,
                ),
              ),
              style: const TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                height: 1.5,
              ),
              maxLines: 1,
            ),
            const Divider(height: 1),
            const SizedBox(height: 8),
            // 内容输入框
            Expanded(
              child: TextField(
                controller: _contentController,
                maxLines: null,
                autofocus: false,
                decoration: const InputDecoration(
                  hintText: '分享此刻的想法...',
                  border: InputBorder.none,
                ),
                style: const TextStyle(
                  fontSize: 16,
                  height: 1.5,
                ),
              ),
            ),
            const SizedBox(height: 16),
            // 创建时间选择区域
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.grey[100],
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      const Icon(Icons.access_time, size: 20, color: Colors.grey),
                      const SizedBox(width: 8),
                      const Text(
                        '创建时间',
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.grey,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      const Spacer(),
                      if (_selectedDateTime != null)
                        IconButton(
                          icon: const Icon(Icons.clear, size: 20),
                          onPressed: _clearDateTime,
                          padding: EdgeInsets.zero,
                          constraints: const BoxConstraints(),
                        ),
                    ],
                  ),
                  const SizedBox(height: 8),
                  InkWell(
                    onTap: _selectDateTime,
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 12,
                        vertical: 10,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(4),
                        border: Border.all(color: Colors.grey[300]!),
                      ),
                      child: Row(
                        children: [
                          Expanded(
                            child: Text(
                              _selectedDateTime != null
                                  ? '${_selectedDateTime!.year}-${_selectedDateTime!.month.toString().padLeft(2, '0')}-${_selectedDateTime!.day.toString().padLeft(2, '0')} ${_selectedDateTime!.hour.toString().padLeft(2, '0')}:${_selectedDateTime!.minute.toString().padLeft(2, '0')}'
                                  : '点击选择日期和时间',
                              style: TextStyle(
                                fontSize: 14,
                                color: _selectedDateTime != null
                                    ? Colors.black87
                                    : Colors.grey,
                              ),
                            ),
                          ),
                          Icon(
                            Icons.calendar_today,
                            size: 18,
                            color: Colors.grey[600],
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
